package com.sophialex.health.record.common.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.ui.forms.widgets.FormToolkit;

import com.sophia.common.pojo.SophiaCommonPojo;
import com.sophia.dict.vo.DictCode;
import com.sophia.health.vo.SystemUser;
import com.sophia.pojo.AbstractModelObject;
import com.sophia.util.DateUtils;
import com.sophialex.health.common.platform.SuperContext;
import com.sophialex.health.common.platform.pojo.Geography;
import com.sophialex.health.person.vo.BusinessCategory;
import com.sophialex.health.person.vo.SoapService;
import com.sophialex.health.record.common.GeographyTreeCombo;
import com.sophialex.health.record.common.GeographyTreeInit;
import com.sophialex.health.record.common.SOAPServiceDispath;
import com.sophialex.health.record.common.bind.CheckboxBindingUtil;
import com.sophialex.health.system.validation.idcardvalidate.IdcardInfoExtractor;

/**
 * 工具类
 * <p>Title:Health</p>
 * <p>CommonUtils</p>
 * 
 * Alex Apr 19, 2011 10:18:28 PM create
 * @author <a href='wanghao924@126.com'>Alex</a>
 * QQ: 873987060;
 * @version 1.0
 */
public class CommonUtils {

	public static void initCombo(Combo combo,String dict,String defaultValue,boolean flag){
		if(combo == null){
			return;
		}
		Set set = SuperContext.dictCache.getCodesByName(dict);
		Iterator it = set.iterator();
		if(flag){
			DictCode selectValue = new DictCode();
			selectValue.setCodeValue("--请选择--");
			selectValue.setCodeNum("-1");
			combo.setData(selectValue.getCodeValue(), selectValue);
			combo.add(selectValue.getCodeValue());
		}
		while(it.hasNext()){
			 DictCode code = (DictCode) it.next();
			 combo.setData(code.getCodeValue(), code);
			 combo.add(code.getCodeValue());
		}
		if(defaultValue != null){
			combo.setText(defaultValue);
		}else{
			combo.select(0);
		}
		
	}
	
	public static void initUserCombo(Combo combo,String defaultValue,boolean flag){
		if(combo == null){
			return;
		}
		if(flag){
			DictCode selectValue = new DictCode();
			selectValue.setCodeValue("--请选择--");
			selectValue.setCodeNum("-1");
			combo.setData(selectValue.getCodeValue(), selectValue);
			combo.add(selectValue.getCodeValue());
		}
		List<SystemUser> userList = SuperContext.userList;
		if(userList != null){
			for(int i = 0; i < userList.size(); i++) {
				DictCode code = new DictCode();
				code.setCodeNum(userList.get(i).getId().toString());
				code.setCodeValue(userList.get(i).getUserName());
				combo.setData(code.getCodeValue(), code);
				combo.add(code.getCodeValue());
			}
		}
		if(defaultValue != null){
			combo.setText(defaultValue);
		}else{
			combo.select(0);
		}
	}
	
	public static void initJDUnitCombo(Combo combo,String defaultValue,boolean flag){
		if(combo == null){
			return;
		}
		if(flag){
			DictCode selectValue = new DictCode();
			selectValue.setCodeValue("--请选择--");
			selectValue.setCodeNum("-1");
			combo.setData(selectValue.getCodeValue(), selectValue);
			combo.add(selectValue.getCodeValue());
		}
		
		DictCode selectValue = new DictCode();
		selectValue.setCodeValue(SuperContext.getHosName());
		selectValue.setCodeNum(SuperContext.getSYS_ORG_ID().toString());
		combo.setData(selectValue.getCodeValue(), selectValue);
		combo.add(selectValue.getCodeValue());
		if(defaultValue != null){
			combo.setText(defaultValue);
		}else{
			combo.select(0);
		}
	}
	
	public static String getUserNameById(Long userId){
		List<SystemUser> userList = SuperContext.userList;
		for(SystemUser user : userList) {
			if(userId.longValue() == user.getId().longValue()){
				return user.getUserName();
			}
		}
		return "";
	}
	
	public static String getValueByNumForDictCode(Long codeNum,String dictName){
		if(codeNum == null || dictName == null){
			return "";
		}
		Set set = SuperContext.dictCache.getCodesByName(dictName);
		Iterator it = set.iterator();
		while(it.hasNext()){
			 DictCode code = (DictCode) it.next();
			 if(code.getCodeNum().equals(codeNum.toString())){
				 return code.getCodeValue();
			 }
		}
		return "";
	}
	
	public static void initCombo(Combo combo,String dict){
		initCombo(combo,dict,null,true);
	}
	public static void initCombo(Combo combo,String dict,String defaultValue){
		initCombo(combo,dict,defaultValue,true);
	}
	
	public static void initCombo(Combo combo,String dict,boolean flag){
		initCombo(combo,dict,null,flag);
	}
	
	public static String getComboText(Combo combo){
		if(combo == null){
			return null;
		}
		return combo.getText();
	}
	
	public static Long getComboValue(Combo combo){
		if(combo == null){
			return null;
		}
		return Long.valueOf(((DictCode)combo.getData(combo.getText())).getCodeNum());
	}
	
	public static void setComboValue(Combo combo,String dict,Long value){
		if(combo != null && value !=null){
			Set set = SuperContext.dictCache.getCodesByName(dict);
			Iterator it = set.iterator();
			while(it.hasNext()){
				 DictCode code = (DictCode) it.next();
				 if(value.toString().equals(code.getCodeNum())){
					 combo.setText(code.getCodeValue());
					 return;
				 }
			}
			combo.select(0);
		}
	}
	
	public static SophiaCommonPojo getCommonPojo(){
		SophiaCommonPojo commonPojo = new SophiaCommonPojo();
		SystemUser user = SuperContext.currentUser;
		Date date = new Date();
		commonPojo.setOrgId(user.getOrgId());
		commonPojo.setOperatorId(user.getId());
		commonPojo.setOpOrgId(user.getOrgId());
		commonPojo.setPtOrgId(user.getOrgId());
		commonPojo.setStatus("A");
		commonPojo.setCreateUserid(user.getId());
		commonPojo.setCreateDate(date);
		commonPojo.setChecksum("0");
		commonPojo.setUpdateTime(date);
		return commonPojo;
	}
	
	public static Date getDateFromDateTime(DateTime datetime){
		if (datetime==null){
			return new Date();
		}
		String datetimeStr = datetime.getYear() + "-" + (datetime.getMonth()+1) + "-" + datetime.getDay();
		Date da  = DateUtils.parseDate(datetimeStr);
		return da;
	}
    
    /**
     * 获得业务类别名称
     * @param id
     * @return
     * @author Alex 
     * Apr 22, 2011 10:43:14 AM create
     */
	public static String getBusTypeName(Long id){
		String name="";
		Map<Long,BusinessCategory> map=SuperContext.businessCategoryMap;
		if(!map.isEmpty()&&id!=null){
			BusinessCategory cate=map.get(id)==null?null:(BusinessCategory)map.get(id);
			if(cate!=null){
				name=cate.getCategoryName();
			}
		}
		return name;
	
	}
	
    /**
     * 
     * 对业务类别进行分组
     * @param list
     * @return
     * @author Alex 
     * Apr 22, 2011 11:12:50 AM create
     */
	public static Map<Long ,List<Long>> getBusTypeGroup(List list){
		Map map=new HashMap();
		if(list!=null&&list.size()>0){
			List subList=new ArrayList();
			for(Iterator it=list.iterator();it.hasNext();){
				Long bustype=(Long)it.next();
				Long subType = getLong(bustype.toString().substring(0,4)+"000000000000");
				if(!subList.contains(subType)){
					subList.add(subType);
				}
			}
			if(subList.size()>0){			
				for(Iterator ite=subList.iterator();ite.hasNext();){
					Long subType=(Long) ite.next();
					List supList=new ArrayList();
					
					for(Iterator it=list.iterator();it.hasNext();){
						Long bustype=(Long)it.next();
						Long sub = getLong(bustype.toString().substring(0,4)+"000000000000");
						if(subType.equals(sub)){
							supList.add(bustype);
						}
					}
					//对子类排序
					List cates = new ArrayList();
					BusinessCategory cate = null;
					Map bcMap = SuperContext.businessCategoryMap;
					for(Iterator iter = supList.iterator();iter.hasNext();){
						Long supId = (Long)iter.next();
						if(!bcMap.isEmpty() && supId != null){
							cate = bcMap.get(supId) == null?null:(BusinessCategory)bcMap.get(supId);
							if(cate.getOrderNum() != null){
								cates.add(cate);
							}
							if(!cates.isEmpty() && cates.size() > 0){
								Collections.sort(cates,new BusinessCategoryComparator());
							}
						}
					}
					if(!cates.isEmpty() && cates.size() > 0){
						for(Iterator itera = cates.iterator();itera.hasNext();){
							BusinessCategory bc = (BusinessCategory)itera.next();
							if(bc != null){
								if(supList.contains(bc.getId())){
									supList.remove(bc.getId());
									supList.add(bc.getId());
								}
							}
						}
					}
					map.put(subType,supList);
				}
			}

		}
		return map;
	}
	
	public static Long getLong(String value) {
		Long lvalue = null;
		if (value != null && !"".equals(value) && !"null".equals(value.trim().toLowerCase())) {
			try {
				lvalue = Long.valueOf(value.trim());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return lvalue;
	}
	
	/**
	 * 选中相应的村委会
	 * @param combo
	 * @param geogId
	 * @author Alex 
	 * Apr 29, 2011 10:36:00 PM create
	 */
	public static void selectGeography(GeographyTreeCombo combo,Long geogId){
		List<Geography> geography = SuperContext.getDsGeographyTreeList();
		getGeography(geography.get(0),combo,null,geogId);
	}
	
   private static void getGeography(Geography geography,GeographyTreeCombo combo_cwh,Geography f,Long geogId){
	    boolean flag=false;
	    if(geography.getBrachs().size()>0){
	    	for(int i = 0; i < geography.getBrachs().size(); i++) {
	    		Geography g = geography.getBrachs().get(i);
				 if(g != null){
					 getGeography(g,combo_cwh,g,geogId);
				 }
			}
	    }else{
	    	if(f.getfTreebh() != null && geogId.toString().equals(f.getfTreebh())){
	    		combo_cwh.setSelection(f);
	    	}
	    }
   }
	   
	public static Map<Long, List<Long>> getAllService(SystemUser systemUser){
		Map dispathmap = SOAPServiceDispath.serviceMap;
		List list = new ArrayList();
		if (!dispathmap.isEmpty()) {
			for (Iterator it = dispathmap.keySet().iterator(); it.hasNext();) {
				Long key = (Long) it.next();
				list.add(key);
			}
	    }
		return getBusTypeGroup(list);
	}
	
	public static List<Long> getBusTypes(Collection coll) {
		List<Long> list = new ArrayList<Long>();
		if (coll != null && coll.size() > 0) {
			for (Iterator<SoapService> it = coll.iterator(); it.hasNext();) {
				SoapService service = (SoapService) it.next();
				if (!list.contains(service.getBusType())) {
					list.add(service.getBusType());
				}
			}
		}
		return list;
	}
	
	public static Button[] initCheckBoxUI(FormToolkit toolkit,Composite composite,Control label,String dictName,int[] width,AbstractModelObject pojo,String property){
		return initCheckBoxUI(toolkit,composite,label,dictName,6,width,pojo,property);
	}
	
	public static Button[] initCheckBoxUI(FormToolkit toolkit,Composite composite,Control label,String dictName,int[] width,AbstractModelObject pojo,String property,int column){
		return initCheckBoxUI(toolkit,composite,label,dictName,6,width,pojo,property,column);
	}
	
	public static Button[] initCheckBoxUI(FormToolkit toolkit,Composite composite,Control label,String dictName,int left,int[] width,AbstractModelObject pojo,String property){
		Set<DictCode> setCode = SuperContext.dictCache.getCodesByName(dictName);
        List<DictCode> codeList = new ArrayList<DictCode>();
        Iterator<DictCode> it = setCode.iterator();
        while(it.hasNext()){
        	codeList.add(it.next());
        }
		Button[] buttons = new Button[codeList.size()];
        for(int i = 0; i < buttons.length; i++) {
        	String title = " " + codeList.get(i).codeValue;
        	buttons[i] = toolkit.createButton(composite, title, SWT.CHECK);
        	FormData fd_button = new FormData();
        	if(label !=null){
        		fd_button.bottom = new FormAttachment(label, 0, SWT.BOTTOM);
        	}
			
        	if(i==0){
            	if(label !=null){
            		fd_button.left = new FormAttachment(label, left);
            	}
        	}else{
        		if(width.length == 1){
        			fd_button.left = new FormAttachment(buttons[i-1],width[0]);
        		}else{
            		fd_button.left = new FormAttachment(buttons[i-1],width[i-1]);
        		}

        		
        	}
        	buttons[i].setLayoutData(fd_button);
		}
        if(pojo != null){
        	  CheckboxBindingUtil checkboxBind = new CheckboxBindingUtil();
        	  checkboxBind.bindCheckBitByBit(buttons, pojo,property,null,true);
        }
        return buttons;
	}
	
	public static Button[] initCheckBoxUI(FormToolkit toolkit,Composite composite,Control label,String dictName
			,int left,int[] width,AbstractModelObject pojo,String property,int column){
		Set<DictCode> setCode = SuperContext.dictCache.getCodesByName(dictName);
        List<DictCode> codeList = new ArrayList<DictCode>();
        Iterator<DictCode> it = setCode.iterator();
        while(it.hasNext()){
        	codeList.add(it.next());
        }
		Button[] buttons = new Button[codeList.size()];
		Button newRow = null;
		Button one = buttons[0];
        for(int i = 0; i < buttons.length; i++) {
        	String title = " " + codeList.get(i).codeValue;
        	buttons[i] = toolkit.createButton(composite, title, SWT.CHECK);
        	FormData fd_button = new FormData();
        	if(label !=null){
        		fd_button.bottom = new FormAttachment(label, 0, SWT.BOTTOM);
        	}
        	if(i!=0){
    			if(i%column==0){
    				newRow = buttons[i];
    				fd_button.top = new FormAttachment(buttons[i-column],30,SWT.TOP);
    				fd_button.left = new FormAttachment(buttons[i-column],0,SWT.LEFT);
    			}else{
    				fd_button.top =  new FormAttachment(newRow,0,SWT.TOP);
    				if(i>column){
    					fd_button.left = new FormAttachment(buttons[i-column],0,SWT.LEFT);
    				}else{
        				if(width.length == 1){
                			fd_button.left = new FormAttachment(buttons[i-1],width[0]);
                		}else{
                    		fd_button.left = new FormAttachment(buttons[i-1],width[i-1]);
                		}
    				}
	
    			}
        	}
        		if(i==0){
                	if(label !=null){
                		fd_button.left = new FormAttachment(label, left);
                	}
            	} 
 
        
        	buttons[i].setLayoutData(fd_button);
		}
        if(pojo != null){
        	  CheckboxBindingUtil checkboxBind = new CheckboxBindingUtil();
        	  checkboxBind.bindCheckBitByBit(buttons, pojo,property,null,true);
        }
        return buttons;
	}
	
	
	
	
	
	public static void initDsGeography(GeographyTreeCombo cmbCommittee,GeographyTreeInit treeObj) {
		List<Geography> list = treeObj.getList();
		if (list != null && list.size() > 0) {
			cmbCommittee.setSelection(list.get(0));
		}
	}
	
	
	public static void initValueByIdCard(String idCardNo,Combo sexCombo,DateTime birthday){
		IdcardInfoExtractor ie = new IdcardInfoExtractor(idCardNo);
        
		if(sexCombo != null && ie.getSex() != null){
			 sexCombo.setText(ie.getGender());
		}
		if(birthday != null && ie.getBirthday() != null){
			Date date = ie.getBirthday();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			birthday.setDate(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
			
		}
	}
	
	public static String calcAge(Date birthday) {
		Date date = birthday;
		long birthYear = date.getYear();
		long birthMonth = date.getMonth();
		long birthDay = date.getDate();
		Date now = new Date();
		long nowYear = now.getYear();
		long nowMonth = now.getMonth();
		long nowDay = now.getDate();
		if (birthYear > nowYear) {
			return null;
		}

		long resultYear = 0;
		long resultMonth = 0;
		long resultDay = 0;

		if (nowMonth > birthMonth || (nowMonth == birthMonth && nowDay >= birthDay)) {
			resultYear = nowYear - birthYear;
			if (nowDay >= birthDay) {
				resultMonth = nowMonth - birthMonth;
				resultDay = nowDay - birthDay;
			} else {
				resultMonth = nowMonth - birthMonth - 1;
				resultDay = 30 - birthDay + nowDay;
			}
		} else {
			resultYear = nowYear - birthYear - 1;
			if (nowDay >= birthDay) {
				resultMonth = 12 - birthMonth + nowMonth;
				resultDay = nowDay - birthDay;
			} else {
				resultMonth = 12 - birthMonth + nowMonth - 1;
				resultDay = 30 - birthDay + nowDay;
			}
		}

		String ageStr = "";
		if (resultYear > 0) {
			if (resultYear > 3) {
				ageStr = new Long(resultYear).toString() + "岁";
			} else {
				ageStr = new Long(resultYear).toString() + "岁" + new Long(resultMonth+1).toString() + "个月";
			}
		} else if (resultMonth > 0) {
			ageStr = new Long(resultMonth).toString() + "个月" + new Long(resultDay).toString() + "天";
		} else if (resultDay >= 0) {
			ageStr = new Long(resultDay).toString() + "天";
		}
		return ageStr;
	}

}


class BusinessCategoryComparator implements Comparator {

	public int compare(Object arg0, Object arg1) {
		BusinessCategory bc1 = (BusinessCategory)arg0;
		BusinessCategory bc2 = (BusinessCategory)arg1;
		int i = 0;
		if(bc1.getOrderNum() != null && bc2.getOrderNum() != null){
			i = (int)(bc1.getOrderNum() - bc2.getOrderNum());
		}
		return i;
	}
  
}